#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    server.py
"""
import logging
# Application is the glue between one or more service definitions, interface and protocol choices.
from spyne.application import Application
# @rpc 修饰器将方法公开为远程过程调用，并声明其接收和返回的数据类型
from spyne.decorator import rpc
# spyne.service.ServiceBase是所有服务定义的基类
from spyne.service import ServiceBase
# 数据类型
from spyne import Integer, Unicode, Array, ComplexModel, Iterable, String
# soap1.1标准
from spyne.protocol.soap import Soap11
# 服务是通过http进行传输的，WsgiApplication将包装Application实例
from spyne.server.wsgi import WsgiApplication
# python内置的wsgi服务器模块：wsgiref，用于创建wsgi服务
from wsgiref.simple_server import make_server


# step1: 自定义数据结构
class Person(ComplexModel):
    name = Unicode
    age = Integer

class PeopleResponse(ComplexModel):
    name = Person
    message = Unicode


# step2: 定义webservice服务
class HelloWorldService(ServiceBase):
    @rpc(Unicode, Integer, _returns=Iterable(Unicode))
    def say_hello(self, name, times):
        for i in range(times):
            yield "Hello %s, It's the %s time to meet you." % (name, i + 1)

    @rpc(Array(Person), _returns=Iterable(Unicode))
    def say_hello_1(self, persons):
        print('-------say_hello_1()--------')
        print(persons)
        if not persons:
            yield 'None'
        for person in persons:
            print('name is : %s, age is %s.' % (person.name, person.age))
            yield 'name is : %s, age is %s.' % (person.name, person.age)


class SelectStudent(ServiceBase):
    @rpc(Array(String),_returns = Iterable(Unicode))
    def selectAllStudent(self,persons):
        print("selectAllStudent")



class HelloWorldService2(ServiceBase):
    @rpc(Array(String), _returns=Iterable(Unicode))
    def say_hello_2(self, persons):
        print("persons: ", persons)
        if not persons:
            yield 'None'
        for person in persons:
            yield person

    @rpc(Person, _returns=PeopleResponse)
    def say_hello_3(self, person):
        if not person:
            return {}
        else:
            # return PeopleResponse(name=People(**person))
            return {
                "name": person,
                "message": 'name is : %s, age is %s.' % (person.name, person.age)
            }

# step3
application = Application([HelloWorldService,HelloWorldService2],
                          'spyne.examples.hello',
                          in_protocol=Soap11(validator='lxml'),
                          out_protocol=Soap11())

# step4:
wsgi_application = WsgiApplication(application)

if __name__ == '__main__':
    host = '127.0.0.1'
    port = 8000

    logging.basicConfig(level=logging.DEBUG)
    # 指定记录器的名称，设置日志记录级别
    logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG)
    logging.info("listening to http://127.0.0.1:8901")
    logging.info("wsdl is at: http://localhost:8901/?wsdl")

    # step5: 创建一个wsgi服务
    server = make_server(host, port, wsgi_application)
    server.serve_forever()